/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.ajz.web;

import com.github.sd4324530.fastweixin.company.api.config.QYAPIConfig;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.CookieUtils;
import com.jeesite.common.web.http.ServletUtils;
import com.jeesite.modules.ajz.entity.*;
import com.jeesite.modules.ajz.service.*;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.sys.wx.fw.utils.ResultTemplateMsgUtil;
import com.jeesite.modules.sys.wx.qy.py.WeixinJSSDKSignUtil;
import com.jeesite.modules.sys.wx.qy.util.QyConfigUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.jeesite.modules.sys.utils.AjzUtils.deepCopy;
import static com.jeesite.modules.sys.utils.Filter.filter;
import static com.jeesite.modules.sys.utils.Timestamp.TIMESTAMP;

/**
 * 出租屋信息Controller
 * @author hhx
 * @version 2019-06-27
 */
@Controller
@RequestMapping(value = "${adminPath}/ajz/ajzHouseInfo")
public class AjzHouseInfoController extends BaseController {

	@Autowired
	private AjzHouseInfoService ajzHouseInfoService;

	@Autowired
	private AjzCheckService ajzCheckService;

	@Autowired
	private EmpUserService empUserService;

	@Autowired
	private AjzModelService ajzModelService;

	@Autowired
	private AjzModelContentService ajzModelContentService;

	@Autowired
	private AjzRecordProcessService ajzRecordProcessService;

	@Autowired
	private AjzNaturalGasService ajzNaturalGasService;

	@Autowired
	private AjzLiquefiedGasService ajzLiquefiedGasService;

	@Autowired
	private OfficeService officeService;

	@Autowired
	private AjzRecordService ajzRecordService;

	//审核结果通知
	@Autowired
	private ResultTemplateMsgUtil resultTemplateMsgUtil;
	/**
	 * 企业信息页面
	 * @param ajzHouseInfo
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "index")
	public String index(AjzHouseInfo ajzHouseInfo, Model model) {
		return "modules/ajz/ajzHouseInfoIndex";
	}

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public AjzHouseInfo get(String id, boolean isNewRecord) {
		return ajzHouseInfoService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("ajz:ajzHouseInfo:view")
	@RequestMapping(value = {"list", ""})
	public String list(AjzHouseInfo ajzHouseInfo, Model model) {
		model.addAttribute("ajzHouseInfo", ajzHouseInfo);
		return "modules/ajz/ajzHouseInfoList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("ajz:ajzHouseInfo:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<AjzHouseInfo> listData(AjzHouseInfo ajzHouseInfo, HttpServletRequest request, HttpServletResponse response) {
		ajzHouseInfo.setPage(new Page<>(request, response));
		Page<AjzHouseInfo> page = ajzHouseInfoService.findPage(ajzHouseInfo); 
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("ajz:ajzHouseInfo:view")
	@RequestMapping(value = "form")
	public String form(AjzHouseInfo ajzHouseInfo, Model model) {
		model.addAttribute("ajzHouseInfo", ajzHouseInfo);
		return "modules/ajz/ajzHouseInfoForm";
	}

	/**
	 * 保存出租屋信息
	 */
	@RequiresPermissions("ajz:ajzHouseInfo:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated AjzHouseInfo ajzHouseInfo) {
		ajzHouseInfoService.save(ajzHouseInfo);
		return renderResult(Global.TRUE, text("保存出租屋信息成功！"));
	}
	
	/**
	 * 删除出租屋信息
	 */
	@RequiresPermissions("ajz:ajzHouseInfo:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(AjzHouseInfo ajzHouseInfo) {
		ajzHouseInfoService.delete(ajzHouseInfo);
		return renderResult(Global.TRUE, text("删除出租屋信息成功！"));
	}

	//==========================================以下是企业号的方法,序号代表流程中所在位置=========================================================

	//记录流程:记录提交，展示记录页面
	@RequestMapping(value = "recordCommit")
	public String recordCommit(AjzHouseInfo ajzHouseInfo, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {

		//生成recordProcessId
		String recordProcessId = UUID.randomUUID().toString().replaceAll("-", "");

		//保存记录信息
		AjzRecord ajzRecord = ajzHouseInfoService.saveCmtRecord(recordProcessId,ajzHouseInfo,request);

		//保存问题项,
		List<AjzCheck> ajzChecksList = ajzHouseInfoService.saveCmtCheck(recordProcessId,request);

		//保存生成文书,返回建议用于推送
		ajzHouseInfoService.saveCmtFile(ajzRecord,ajzChecksList,ajzHouseInfo,request);

		//========================================================服务号消息推送=======================================================================================
		try{
			String opinion = "";
			if(StringUtils.isNotBlank(opinion) && ajzHouseInfo!=null && StringUtils.isNotBlank(ajzHouseInfo.getOpenid())){
				//1.获取问题项目
				opinion = opinion.substring(0, 11)+"......";
				//2.封装消息内容
				Map<String, Object> map = new HashMap<>();
				map.put("first","您有一条新的检查消息通知：\r\n");
				map.put("keyword1","安全生产");
				map.put("keyword2",request.getParameter("starTime"));
				map.put("keyword3",opinion+"\r\n");
				map.put("remark","详情查看具体内容");
				//3.发送消息
				resultTemplateMsgUtil.sendWord(ajzHouseInfo.getOpenid(),map);
			}
		}catch (Exception e){
			System.out.println("erro:"+e);
		}finally {
			ServletUtils.redirectUrl(request, response, adminPath + "/ajz/ajzBaseinfo/searchName?id=" + ajzHouseInfo.getId());
			return "null";
		}

	}

	//记录流程:跳转提交记录页面
	@RequestMapping(value = "record")
	public String record(AjzHouseInfo ajzHouseInfo, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

		//获取检查人员信息
		String userCode = CookieUtils.getCookie(request, "userId");
		if(StringUtils.isBlank(userCode)){
			userCode = request.getParameter("user");
		}
		User user = UserUtils.getByLoginCode(userCode);

		//测试从其他地方进来
		if (user == null) {
			user = UserUtils.getByLoginCode("admin");
		}

		//获取上次的检查记录
		List<AjzCheck> ajzChecks= new ArrayList<>();
		List<AjzCheck> orderList=new ArrayList<>();
		List<AjzCheck> rectofication = new ArrayList<>();
		AjzRecord ajzRecord = ajzRecordService.findInfoById(ajzHouseInfo.getId(),request.getParameter("tableType"));
		if(ajzRecord !=null){
			ajzChecks = ajzCheckService.findListByRecordProcessId(ajzRecordProcessService.findForNum(ajzRecord.getNumber()).getId());
			//将list进行深度复制
			orderList = deepCopy(ajzChecks);
			rectofication = deepCopy(ajzChecks);
			//过滤掉不要的隐患问题
			orderList = filter(orderList, "2");
			rectofication = filter(rectofication, "1");
		}

		//获取上次的检查点图片和隐患图片
		String checkUrls =  ajzRecord == null ? "" : ajzRecord.getScenePic();
		String dangerUrls =  ajzRecord == null ? "" : ajzRecord.getDangerPic();
		String[] ckls = null;
		String[] dgls = null;
		if (StringUtils.isNotBlank(checkUrls)) {
			ckls = checkUrls.split(";");
		}
		if (StringUtils.isNotBlank(dangerUrls)) {
			dgls = dangerUrls.split(";");
		}

		//获取当前用户所在机构的其他用户
		EmpUser empUser = empUserService.get(user.getUserCode());
		Employee employee = new Employee();
		if (empUser != null) {
			employee = empUser.getEmployee();
		}

		Employee otherUser = new Employee();
		otherUser.setOffice(employee.getOffice());

		EmpUser empUser1 = new EmpUser();
		empUser1.setEmployee(otherUser);

		List userList = empUserService.findList(empUser1);

		model.addAttribute("userList", userList); //返回执法人员的列表
		model.addAttribute("ckls", ckls);
		model.addAttribute("dgls", dgls);
		model.addAttribute("ajzChecks", ajzChecks); //返回复查信息
		model.addAttribute("orderList", orderList); //责令项list
		model.addAttribute("rectofication", rectofication); //待整改项list
		model.addAttribute("user", user);
		model.addAttribute("ajzHouseInfo", ajzHouseInfo);
		model.addAttribute("record", ajzRecord);
		model.addAttribute("tableType", request.getParameter("tableType"));

		//cookie 存值为ajz_aqsc
		CookieUtils.setCookie(response, "house", ajzHouseInfo.getId());

		//获得微信jssdk签名等
		QYAPIConfig qyapiConfig = QyConfigUtil.getQYAPIConfig();
		String jsapi_ticket = qyapiConfig.getJsApiTicket();

		String queryString = request.getQueryString();
		String url2 = "http://" + request.getServerName() // 服务器地址
				+ request.getContextPath() // 项目名称
				+ request.getServletPath(); // 请求页面或其他地址
		if (queryString != null) {
			url2 += "?" + queryString;
		}
		Map<String, String> sign = WeixinJSSDKSignUtil.sign(jsapi_ticket, url2);

		//获取隐患模板的信息,包括类型和内容

		AjzModel ajzModel = new AjzModel();
		AjzModelContent ajzModelContent = new AjzModelContent();
		ajzModel.setBaseType(request.getParameter("tableType"));
		List<AjzModel> modelList = ajzModelService.findList(ajzModel);
		List<AjzModelContent> ajzModelContentList = new ArrayList<>();

		Map danModel = new LinkedHashMap<>();
		for (AjzModel am:modelList) {
			ajzModelContent.setModelId(am.getId());
			ajzModelContentList = ajzModelContentService.findList(ajzModelContent);
			danModel.put(am.getDangerType(), ajzModelContentList);
		}

		model.addAttribute("danModel", danModel);
		model.addAttribute("appId", QyConfigUtil.apiConfig.getCorpid());
		model.addAttribute("nonceStr", sign.get("nonceStr"));
		model.addAttribute("timestamp", sign.get("timestamp"));
		model.addAttribute("signature", sign.get("signature"));

		//开始检查的时间
		model.addAttribute("starTime", DateUtils.getDateTime());

		//时间戳
		model.addAttribute("Timestamp", TIMESTAMP);

		return "modules/ajz/mobile/table_house";
	}

	/**
	 * 跳转至专题页
	 * @param model
	 * @return
	 */
	@RequestMapping({"typeHouse"})
	public String typeHouse(Model model){
		model.addAttribute("Timestamp", TIMESTAMP);//时间戳
		model.addAttribute("tableType","ajzHouseInfo");
		return "modules/ajz/mobile/type_house";
	}
	/**
	 * 实时获取店面专题的数据信息
	 * @param status
	 * @return
	 */
	@RequestMapping("detailsMap")
	@ResponseBody
	public List<?> etailsMap(@Param("status") String status,@Param("dangerType") String dangerType){
		List<AjzHouseInfo> allList = new ArrayList<>();
		AjzHouseInfo title = new AjzHouseInfo();
		AjzHouseInfo ajzHouseInfo = new AjzHouseInfo();
		//设置查询条件为企业
		AjzRecord ajzRecord = new AjzRecord();
		ajzRecord.setStatus("0");//设置企业的记录为未删除的
		ajzRecord.setBaseType("house");//设置企业类型，用于查询企业类型的值
		ajzRecord.setTableType(dangerType);
		//查询有排查过的对应企业，默认为所有
		ajzHouseInfo.setAjzRecord(ajzRecord);
		//获取默认页数
		Page page = new Page();
		page.setPageSize(10);
		page.setPageNo(1);
		ajzHouseInfo.setPage(page);
		/*1.获取标题栏数据*/
		//全部
		int all =ajzHouseInfoService.findAllList().size();
		//待整改
		ajzHouseInfo.getAjzRecord().setCheckStatus("1");
		int uncheck = (int)ajzHouseInfoService.findCount(ajzHouseInfo);
		ajzHouseInfo.getAjzRecord().setCheckStatus("2");
		uncheck += (int)ajzHouseInfoService.findCount(ajzHouseInfo);
		//已整改
		ajzHouseInfo.getAjzRecord().setCheckStatus("3");
		ajzHouseInfo.getAjzRecord().setTableType(dangerType);
		int checked = (int)ajzHouseInfoService.findCount(ajzHouseInfo);
		//待排查
		int uninspect =all-uncheck-checked;
		title.setAll(all);
		title.setUninspect(uninspect);
		title.setUncheck(uncheck);
		title.setChecked(checked);
		title.setStatus(status);//这里临时用作表示选中的标题栏

		/*2.获取对应过滤的数据列表*/
		switch (Integer.parseInt(status)){
			case 0://全部
				allList = ajzHouseInfoService.findAllList();
				break;
			case 1://待排查
				List<String> recordBaseId = new ArrayList();
				List<String> houseBaseId = new ArrayList();

//                ajzRecord.setCheckStatus("4");
				for(AjzRecord record:ajzRecordService.findList(ajzRecord)){
					recordBaseId.add(record.getBaseId());
				}
				for(AjzHouseInfo houseInfo:ajzHouseInfoService.findAllList()){
					houseBaseId.add(houseInfo.getId());
				}

				houseBaseId.removeAll(recordBaseId);


				//同时包含检查状态为4的
				ajzRecord.setCheckStatus("4");
				recordBaseId.clear();
				for(AjzRecord record:ajzRecordService.findList(ajzRecord)){
					recordBaseId.add(record.getBaseId());
				}
				houseBaseId.addAll(recordBaseId);
				//获取
				for(String id:houseBaseId){
					allList.add(ajzHouseInfoService.getById(id));
				}
				break;
			case 2://待整改
				ajzHouseInfo.getAjzRecord().setCheckStatus("1");
				allList = ajzHouseInfoService.findList(ajzHouseInfo);

				//将状态为 1和2的有隐患问题,合并
				ajzHouseInfo.getAjzRecord().setCheckStatus("2");
				allList.addAll(ajzHouseInfoService.findList(ajzHouseInfo));

				break;
			case 3://已整改
				ajzHouseInfo.getAjzRecord().setCheckStatus("3");
				allList = ajzHouseInfoService.findList(ajzHouseInfo);
				break;
		}

		/*如果存在数据则给标题栏赋值*/
		if(title.getAll()!=0){
			allList.add(title);
		}

		return allList;
	}

	@RequestMapping(value = "addHouse")
	public String addHouse(AjzHouseInfo ajzHouseInfo, AjzNaturalGas ajzNaturalGas, AjzLiquefiedGas ajzLiquefiedGas, HttpServletRequest request, HttpServletResponse response, Model model) {
		//获取用户数据
		String userId = QyConfigUtil.getUserId(request, response);
		//传入出租屋数据
		ajzHouseInfo.setChargePerson(request.getParameter("czwChargePerson"));
		ajzHouseInfo.setChargePersonTel(request.getParameter("czwChargePersonTel"));
		ajzHouseInfo.setContactPerson(request.getParameter("czwContactPerson"));
		ajzHouseInfo.setContactPersonTel(request.getParameter("czwContactPersonTel"));
		ajzHouseInfo.setArea(request.getParameter("czwArea"));
		ajzHouseInfo.setFloorCount(request.getParameter("czwFloorCount"));
		ajzHouseInfo.setAddr(request.getParameter("czwAddr"));



		//传入用户数据
		ajzHouseInfo.setUpdateBy(userId);
		ajzHouseInfo.setCreateBy(userId);
		ajzNaturalGas.setCreateBy(userId);
		ajzNaturalGas.setUpdateBy(userId);
		ajzLiquefiedGas.setCreateBy(userId);
		ajzLiquefiedGas.setUpdateBy(userId);



		//记录的创建者默认为system，所以ajzRecord可以不用设置system。ajzRecord此处必须设置为system的原因是未排查的数据不需要被统计（及按照人名统计时，可以不计入统计内）
//		AjzRecord ajzRecord = new AjzRecord();
//		ajzRecord.setCheckStatus("0");
//		ajzRecord.setBaseType("house");
//		ajzRecord.setTableType("ajz_house");//(临时)
//		ajzHouseInfo.setAjzRecord(ajzRecord);
//		String signboardPic = request.getParameter("imgBox2");
//		String enterprisePicture = request.getParameter("imgBox3");

		String officeName = EmpUtils.getOffice(ajzHouseInfo.getOffice().getOfficeCode()).getOfficeName();

		//创建保存在文件管理器中的文件路径
		String filePath = Global.getUserfilesBaseDir(officeName + File.separator + "出租屋" + File.separator + ajzHouseInfo.getAddr() + File.separator);
		//创建保存数据库的图片路径
		String savePath = request.getContextPath() + File.separator + "userfiles" + File.separator + officeName + File.separator + "门店" + File.separator + ajzHouseInfo.getAddr() + File.separator;
		FileUtils.createDirectory(filePath);


////        保存户外照片
//		if (!StringUtils.isBlank(signboardPic)) {
//			signboardPic = DloadImgUtil.downloadMedia(QyConfigUtil.getAccessToken(), "outdoor", signboardPic, savePath, filePath);
//		}
//		ajzHouseInfo.setSignboardPic(signboardPic);
		ajzHouseInfo.setCycleIndex("1");
		ajzHouseInfo.setCheckStatus("0"); //默认为未检查

		//需要给创建的东西添加用户
		ajzHouseInfoService.save(ajzHouseInfo);
//        保存记录需要添加企业的id，所以需要放在企业保存之后
		//获取出租屋id
		String ajzStoreInfoId = ajzHouseInfo.getId();
		//保存信息
//        ajzRecord.setBaseId(ajzStoreInfoId);
//        ajzRecordService.save(ajzRecord);
//        //recordProcess也需添加一条
//        ajzRecordProcessService.saveRecord(ajzRecord);
		//保存天然气的信息
		ajzNaturalGas.setBaseId(ajzStoreInfoId);
		ajzNaturalGasService.save(ajzNaturalGas);
		//保存液化气的信息
		ajzLiquefiedGas.setBaseId(ajzStoreInfoId);
		ajzLiquefiedGasService.save(ajzLiquefiedGas);


		ServletUtils.redirectUrl(request, response, adminPath + "/ajz/ajzBaseinfo/searchName?id=" + ajzHouseInfo.getId());

		return null;
	}

	//修改:跳转到出租屋修改页面
	@RequestMapping(value = "updateInfo")
	public String updateInfo(AjzHouseInfo ajzHouseInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
		//查询企业的基本信息
		model.addAttribute("ajzHouseInfo",ajzHouseInfo);
		//或者默认一个父级机构的名称
		Office office = new Office();
		office.setParentCode(Global.getConfig("ajz.add.store.officeCode"));
//		office.setParentCode(ajzHouseInfo.getOffice().getParentCode());
		List<Office> officeList = officeService.findList(office);
		model.addAttribute("officeList",officeList);
		//获得微信jssdk签名等
		QyConfigUtil.getJSSDKSign(request,model);
		//时间戳
		model.addAttribute("Timestamp", TIMESTAMP);
		return "modules/ajz/mobile/update_house_baseinfo";
	}

	//修改:执行企业修改
	@RequestMapping(value = "updateHouseInfo")
	public String updateHouseInfo(AjzHouseInfo ajzHouseInfo,HttpServletRequest request, HttpServletResponse response, Model model) {
		//获取用户数据
		String userId = QyConfigUtil.getUserId(request,response);
		if(userId==null){
			userId = "system";
		}
		//传入用户数据
		ajzHouseInfo.setUpdateBy(userId);
		ajzHouseInfo.getAjzNaturalGas().setUpdateBy(userId);
		ajzHouseInfo.getAjzLiquefiedGas().setUpdateBy(userId);

		//创建保存在文件管理器中的文件路径
		String filePath =  Global.getUserfilesBaseDir(ajzHouseInfo.getOffice().getOfficeName() + File.separator + "出租屋" + File.separator +ajzHouseInfo.getAddr() + File.separator );
		//创建保存数据库的图片路径
		String savePath = request.getContextPath() + File.separator +"userfiles"+ File.separator + ajzHouseInfo.getOffice().getOfficeName() + File.separator + "企业" + File.separator +ajzHouseInfo.getAddr() + File.separator;
		FileUtils.createDirectory(filePath);

		//需要给创建的东西添加用户
		ajzHouseInfoService.update(ajzHouseInfo);
		ajzNaturalGasService.update(ajzHouseInfo.getAjzNaturalGas());
		ajzLiquefiedGasService.update(ajzHouseInfo.getAjzLiquefiedGas());

		ServletUtils.redirectUrl(request, response, adminPath + "/ajz/ajzBaseinfo/searchName?id=" + ajzHouseInfo.getId());

		return null;
	}


	//后台出租屋导出
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportHouse")
	public void exportHouse(HttpServletResponse response,AjzHouseInfo ajzHouseInfo) {

		List<AjzHouseInfo> houseList = ajzHouseInfoService.findList(ajzHouseInfo);
		String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try (ExcelExport ee = new ExcelExport("用户数据", AjzHouseInfo.class)) {
			ee.setDataList(houseList).write(response, fileName);
		}
	}
}